"""接口依赖（模型加载、权限校验）"""
"""
API依赖项定义
"""
from typing import Dict, Any
from datetime import datetime
import threading

from fin_senti_entity_platform.utils.config_loader import get_config
from fin_senti_entity_platform.utils.logger import Logger
from fin_senti_entity_platform.service_deployment.cache.cache_manager import CacheManager
from fin_senti_entity_platform.service_deployment.degradation.model_selector import ModelSelector
from fin_senti_entity_platform.service_deployment.service_monitor.metrics_exporter import MetricsExporter
from fin_senti_entity_platform.service_deployment.cost_optimization.peak_scheduler import PeakScheduler
from fin_senti_entity_platform.model_development.sentiment_analysis.deepseek_sentiment import DeepSeekSentimentModel
from fin_senti_entity_platform.model_development.entity_recognition.bert_crf_ner import BertCRFNER
from fin_senti_entity_platform.model_development.model_monitor.performance_tracker import PerformanceTracker
from fin_senti_entity_platform.utils.data_security import DataSecurity

# 初始化日志
logger = Logger().get_logger(__name__)

class ModelManager:
    """模型管理器，负责管理和调用各种模型"""
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(ModelManager, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        # 确保初始化只执行一次
        with self._lock:
            if not hasattr(self, 'initialized'):
                self.initialized = True
                self.config = get_config()
                self.models = {}
                self.model_selector = ModelSelector(self.config)
                self.metrics_exporter = MetricsExporter(self.config)
                self.peak_scheduler = PeakScheduler(self.config)
                self.cache_manager = CacheManager(self.config)
                self.security_manager = DataSecurity(self.config)
                
                # 初始化模型
                self._init_models()
                
    def _init_models(self):
        """初始化所有模型"""
        logger.info("开始初始化模型...")
        
        # 初始化情感分析模型
        try:
            sentiment_config = self.config.get('model', {}).get('deepseek', {})
            self.models['sentiment'] = DeepSeekSentimentModel(sentiment_config)
            logger.info("情感分析模型初始化成功")
        except Exception as e:
            logger.error(f"情感分析模型初始化失败: {str(e)}")
        
        # 初始化实体识别模型
        try:
            entity_config = self.config.get('model', {}).get('entity_recognition', {})
            self.models['entity'] = BertCRFNER(entity_config)
            logger.info("实体识别模型初始化成功")
        except Exception as e:
            logger.error(f"实体识别模型初始化失败: {str(e)}")
            
    def recognize_entities(self, text: str) -> list:
        """识别文本中的实体"""
        # 检查缓存
        cache_key = f"entity_{hash(text)}"
        cached_result = self.cache_manager.get(cache_key)
        if cached_result:
            logger.debug("从缓存获取实体识别结果")
            return cached_result
        
        # 选择模型
        model_type = self.model_selector.select_model('entity', text_length=len(text))
        
        if model_type not in self.models:
            raise Exception(f"模型类型不存在: {model_type}")
        
        # 调用模型
        result = self.models[model_type].predict(text)
        
        # 缓存结果
        self.cache_manager.set(cache_key, result)
        
        return result
        
    def analyze_sentiment(self, text: str, entities: list) -> list:
        """分析文本中实体的情感"""
        # 检查缓存
        cache_key = f"sentiment_{hash(text)}_{hash(str(entities))}"
        cached_result = self.cache_manager.get(cache_key)
        if cached_result:
            logger.debug("从缓存获取情感分析结果")
            return cached_result
        
        # 选择模型
        model_type = self.model_selector.select_model('sentiment', text_length=len(text), entity_count=len(entities))
        
        if model_type not in self.models:
            raise Exception(f"模型类型不存在: {model_type}")
        
        # 调用模型
        result = self.models[model_type].predict(text, entities)
        
        # 缓存结果
        self.cache_manager.set(cache_key, result)
        
        return result
        
    def batch_analyze_sentiment(self, texts: list, entities_list: list) -> list:
        """批量分析文本中实体的情感"""
        results = []
        
        for i, (text, entities) in enumerate(zip(texts, entities_list)):
            try:
                result = self.analyze_sentiment(text, entities)
                results.append(result)
            except Exception as e:
                logger.error(f"批量处理第{i}个文本失败: {str(e)}")
                results.append([])
                
        return results
        
    def get_model_status(self, model_type: str) -> Dict[str, Any]:
        """获取模型状态"""
        if model_type not in self.models:
            return {'status': 'not_initialized'}
        
        model = self.models[model_type]
        
        # 获取性能指标
        metrics = performance_tracker.get_average_metrics(model_type)
        
        return {
            'status': 'ready',
            'is_trained': getattr(model, 'is_trained', False),
            'last_updated': datetime.now(),
            'performance_metrics': metrics
        }
        
    def record_performance(self, model_type: str, **metrics) -> None:
        """记录模型性能指标"""
        # 通过性能追踪器记录
        performance_tracker.record_batch_metrics(metrics, batch_size=1, model_type=model_type)
        
        # 导出到监控系统
        self.metrics_exporter.export_model_metrics(model_type, metrics)
        
    def warmup_models(self) -> None:
        """预热模型"""
        logger.info("开始预热模型...")
        
        # 简单的预热文本
        warmup_text = "这是一段用于模型预热的测试文本，包含一些金融相关的内容，如股票、债券、基金等金融产品。"
        
        for model_type in self.models:
            try:
                if model_type == 'entity':
                    self.recognize_entities(warmup_text)
                elif model_type == 'sentiment':
                    # 为情感分析创建一些虚拟实体
                    dummy_entities = [{'start': 20, 'end': 22, 'type': 'product', 'text': '股票'}]
                    self.analyze_sentiment(warmup_text, dummy_entities)
                
                logger.info(f"模型 {model_type} 预热成功")
            except Exception as e:
                logger.error(f"模型 {model_type} 预热失败: {str(e)}")


class SecurityManager:
    """安全管理器，负责API安全相关功能"""
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(SecurityManager, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        with self._lock:
            if not hasattr(self, 'initialized'):
                self.initialized = True
                self.config = get_config()
                self.data_security = DataSecurity(self.config)
    
    def check_data_security(self, text: str) -> bool:
        """检查数据安全性"""
        return self.data_security.check_text_security(text)
    
    def mask_sensitive_data(self, text: str) -> str:
        """掩码敏感数据"""
        return self.data_security.mask_sensitive_info(text)


# 依赖项工厂函数
def get_model_manager():
    """获取模型管理器实例"""
    return ModelManager()

def get_security_manager():
    """获取安全管理器实例"""
    return SecurityManager()